package main

// fasthttpsession use memory provider

import (
	"log"
	"os"

	"github.com/phachon/fasthttpsession"
	"github.com/phachon/fasthttpsession/memory"
	"github.com/valyala/fasthttp"
)

// 默认的 session 全局配置
var session = fasthttpsession.NewSession(fasthttpsession.NewDefaultConfig())

func main() {
	// 必须在使用之前指定 session 的存储
	err := session.SetProvider("memory", &memory.Config{})
	if err != nil {
		log.Println(err.Error())
		os.Exit(1)
	}
	addr := ":8086"
	log.Println("fasthttpsession example server listen: " + addr)

	// fasthttp start listen serve
	err = fasthttp.ListenAndServe(addr, requestHandle)
	if err != nil {
		log.Println("listen server error :" + err.Error())
	}
}

// request handler
func requestHandle(ctx *fasthttp.RequestCtx) {
	// start session
	sessionStore, err := session.Start(ctx)
	if err != nil {
		ctx.SetBodyString(err.Error())
		return
	}
	// 必须 defer sessionStore.save(ctx)
	defer sessionStore.Save(ctx)

	sessionStore.Set("name", "fasthttpsession")

	ctx.SetBodyString(fmt.Sprintf("fasthttpsession setted key name= %s ok", sessionStore.Get("name").(string)))
}
